package com.htandroid.htandroid.aty;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.model.AbMenuItem;
import com.ab.soap.AbSoapListener;
import com.ab.soap.AbSoapParams;
import com.ab.soap.AbSoapUtil;
import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskListener;
import com.ab.task.AbTaskObjectListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.ioc.AbIocView;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.adapter.ListPopAdapter;
import com.htandroid.htandroid.entity.SplcLinesChar;
import com.htandroid.htandroid.entity.UffjqgdList;
import com.htandroid.htandroid.entity.UffjqgdList_detail;
import com.htandroid.htandroid.entity.Vendor;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.htandroid.sys.Basenvo;
import com.htandroid.htandroid.sys.InstorageURL;
import com.htandroid.htandroid.sys.User;
import com.htandroid.htandroid.webservice.BuildQgdDjdetailXMLService;
import com.htandroid.htandroid.webservice.XMLQgdDjdetail;
import com.htandroid.htandroid.webservice.abXMLQgdDjdetail;
import com.htandroid.htandroid.webservice.abXMLSplcCharlist;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

/**
 * Created by lkp on 2015/12/4.
 */
public class qgdsp_detail extends AbActivity implements
        AbPullToRefreshView.OnHeaderRefreshListener, AbPullToRefreshView.OnFooterLoadListener {
    public MyApplication myApplication;
    private ArrayList<UffjqgdList_detail> qgdlist_detail;
    private int icurrentrow;
    private UffjqgdList qgdtitle;
    private UffjqgdList_detail qgds;
    int textcolor_old;
    private ArrayList<Vendor> venlist;
    private ArrayList<SplcLinesChar> splclineslist;
    private ArrayAdapter<String> adapter_splc;//账套下拉列表
    ArrayList<String> list_splc = new ArrayList<String>();
    String listtype = "0";
    private TextView tv_currentrow;

    private AbTitleBar mAbTitleBar = null;
    private View rightView1 = null;
    private View rightView2 = null;
    private View rightView3 = null;

    private AbLoadDialogFragment mDialogFragment = null;
    private PopupWindow popupWindow;
    private ListView popListView;
    private View popView;

    @AbIocView(id = R.id.etSearch)
    EditText etSearch;
    @AbIocView(id = R.id.iamount_tv)
    EditText iamount_tv;
    @AbIocView(id = R.id.cdisapprovereason_et)
    EditText cdisapprovereason_et;
    @AbIocView(id = R.id.iquantity_tv)
    EditText iquantity_tv;
    @AbIocView(id = R.id.cven_tv)
    EditText cven_tv;
    @AbIocView(id = R.id.iprice_et)
    EditText iprice_et;
    @AbIocView(id = R.id.tv_undo, click = "btnClick")
    TextView tv_undo;
    @AbIocView(id = R.id.cinvname_tv)
    TextView cinvname_tv;
    @AbIocView(id = R.id.tv_check, click = "btnClick")
    TextView tv_check;
//    @AbIocView(id = R.id.mPullRefreshView)
//    AbPullToRefreshView mAbPullToRefreshView;
    @AbIocView(id = R.id.splcstep_sp)
    Spinner splcstep_sp;
    @AbIocView(id = R.id.cinvunit_tv)
    TextView cinvunit_tv;
    @AbIocView(id = R.id.cinvstd_tv)
    TextView cinvstd_tv;
    @AbIocView(id = R.id.iqgq_tv)
    TextView iqgq_tv;
    @AbIocView(id = R.id.bapprove_rg)
    RadioGroup bapprove_rg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.layout_qgdsp_detail);
        myApplication = (MyApplication) abApplication;//获得我们的应用程序全局变量
        initview();
        getsplc();
    }

    public void btnClick(View v) {
        switch (v.getId()) {
            case R.id.tv_undo:
                qgd_uncheck(v);
                break;
            case R.id.tv_check:
                qgdsp_check(v);
                break;
        }
    }

    //初始化
    private void initview() {
        mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText("部门请购明细");
        mAbTitleBar.setLogo(R.drawable.icon_back);
        mAbTitleBar.getLogoView().setLayoutParams(new LinearLayout.LayoutParams(58, 57));
        mAbTitleBar.getLogoView().setFocusable(true);
        mAbTitleBar.getLogoView().setFocusableInTouchMode(true);
        mAbTitleBar.setTitleBarBackground(R.color.common_title);
        mAbTitleBar.setTitlePadding(118, 0, 0, 0);

        mAbTitleBar.clearRightView();
        rightView1 = mInflater.inflate(R.layout.btn_abs_back, null);
        mAbTitleBar.addRightView(rightView1);
        rightView2 = mInflater.inflate(R.layout.tv_currentrow, null);
        mAbTitleBar.addRightView(rightView2);
        rightView3 = mInflater.inflate(R.layout.btn_abs_forward, null);
        mAbTitleBar.addRightView(rightView3);
        tv_currentrow = (TextView) rightView2.findViewById(R.id.tv_currentrow);
        tv_currentrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                more_list(v);
            }
        });

        // 设置监听器
//        mAbPullToRefreshView.setOnHeaderRefreshListener(this);
//        mAbPullToRefreshView.setOnFooterLoadListener(this);
//        // 设置进度条的样式
//        mAbPullToRefreshView.getHeaderView().setHeaderProgressBarDrawable(
//                this.getResources().getDrawable(R.drawable.progress_circular));
//        mAbPullToRefreshView.getFooterView().setFooterProgressBarDrawable(
//                this.getResources().getDrawable(R.drawable.progress_circular));
        // 显示进度框
//        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.layout.view_dialog_loading, "正在加载...");
//        mDialogFragment.setAbDialogOnLoadListener(new AbDialogFragment.AbDialogOnLoadListener() {
//
//            @Override
//            public void onLoad() {
//                refreshTask();
//            }
//        });

        refreshTask();
        etSearch.clearFocus();
        tv_undo.setText("消审");
        //读取文本颜色
        textcolor_old = iquantity_tv.getCurrentTextColor();
        //进入窗口时,所有控件处于不可编辑状态,下拉隐藏
        showwin(false);
        //获取传递的对象参数
        qgdtitle = (UffjqgdList) getIntent().getSerializableExtra("uffjqgds");
        listtype = getIntent().getExtras().getString("listtype");

        //单价修改的监听
        iprice_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    String iquantity = iquantity_tv.getText().toString();
                    String iprice = iprice_et.getText().toString();
                    if (iquantity == null || iquantity.equals("") || iprice.equals("")) {
                        iamount_tv.setText(Basenvo.customFormat("######.00##", "0"));
                    } else {
                        iamount_tv.setText(Basenvo.customFormat("######.00##", Double.valueOf(iquantity) * Double.valueOf(iprice)));
                    }
                }
                return false;
            }
        });

        //单价焦点变化
        iprice_et.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                } else {
                    String iquantity = iquantity_tv.getText().toString();
                    String iprice = iprice_et.getText().toString();
                    if (iquantity == null || iquantity.equals("") || iprice.equals("")) {
                        iamount_tv.setText(Basenvo.customFormat("######.00##", "0"));
                    } else {
                        iamount_tv.setText(Basenvo.customFormat("######.00##", Double.valueOf(iquantity) * Double.valueOf(iprice)));
                    }
                }
            }
        });

        //通过数量修改的监听
        iquantity_tv.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    String iquantity = iquantity_tv.getText().toString();
                    String iprice = iprice_et.getText().toString();
                    if (iquantity == null || iquantity.equals("") || iprice.equals("")) {
                        iamount_tv.setText(Basenvo.customFormat("######.00##", "0"));
                    } else {
                        iamount_tv.setText(Basenvo.customFormat("######.00##", Double.valueOf(iquantity) * Double.valueOf(iprice)));
                    }
                }
                return false;
            }
        });

        //通过数量焦点变化
        iquantity_tv.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                } else {
                    String iquantity = iquantity_tv.getText().toString();
                    String iprice = iprice_et.getText().toString();
                    if (iquantity == null || iquantity.equals("") || iprice.equals("")) {
                        iamount_tv.setText(Basenvo.customFormat("######.00##", "0"));
                    } else {
                        iamount_tv.setText(Basenvo.customFormat("######.00##", Double.valueOf(iquantity) * Double.valueOf(iprice)));
                    }
                }
            }
        });

        //获取下拉列表内容,然后根据其中内容来设置明细数据.
        splcstep_sp.setPrompt("请选择步骤");
        adapter_splc = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list_splc);
        splcstep_sp.setAdapter(adapter_splc);
        // 注册下拉事件
        splcstep_sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                Spinner mstep = (Spinner) parent;
                int checktag = 0;
                //获取账套列表当前选中值,然后刷新年度
                String step_choose = mstep.getSelectedItem().toString();
                if (!splclineslist.isEmpty()) {
                    for (int j = 0; j < splclineslist.size(); j++) {
                        boolean canuncheck = true;
                        SplcLinesChar splclines = splclineslist.get(j);
                        String displayname = "(" + splclines.getCharcode() + ")" + splclines.getCharname();
                        //显示当前待审字样式
                        if (checktag == 0 && splclines.getCchecker().equals("")) {
                            checktag = 1;
                            displayname = displayname + "[当前待审]";
                        }
                        //寻找流程所在的列表行
                        if (displayname.equals(step_choose)) {
                            //设置tag
                            splcstep_sp.setTag(String.valueOf(j));
                            //变更步骤后，刷新列表
                            refreshTask();
                            //根据标记，来处理审核和消审按钮的显示
                            if (checktag == 1) {
                                //待审
                                tv_check.setVisibility(View.VISIBLE);
                                tv_undo.setVisibility(View.GONE);
                            } else if (checktag == 0) {
                                //不是最后一步已审
                                if (j < (splclineslist.size() - 1)) {
                                    //下一步不是待审或者当前步骤是请购定价
                                    if (!splclineslist.get(j + 1).getCchecker().equals("") || splclines.getCharcode().equals("000"))
                                        canuncheck = false;
                                }
                                if (canuncheck) {
                                    tv_check.setVisibility(View.GONE);
                                    tv_undo.setVisibility(View.VISIBLE);
                                } else {
                                    tv_check.setVisibility(View.GONE);
                                    tv_undo.setVisibility(View.GONE);
                                }
                            } else {
                                tv_check.setVisibility(View.GONE);
                                tv_undo.setVisibility(View.GONE);
                            }
                            break;
                        }
                        if (checktag == 1) {
                            //把这个标记加1，表示未审流程。
                            checktag = 2;
                        }
                    }
                }
                //修改字体颜色
                TextView v1 = (TextView) view;
                v1.setTextColor(textcolor_old); //可以随意设置自己要的颜色值
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        //弹出窗口
        popView = mInflater.inflate(R.layout.list_pop, null);
        popListView = (ListView) popView.findViewById(R.id.pop_list);
        popupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        AnimationSet animationSet = new AnimationSet(true);
        ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 1, 1, Animation.ZORDER_BOTTOM, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animationSet.setDuration(250);
        animationSet.addAnimation(scaleAnimation);
        popView.startAnimation(animationSet);
        ImageView more_close = (ImageView) popView.findViewById(R.id.item_close);
        more_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        ImageView titlemore_iv = (ImageView) findViewById(R.id.titlemore_iv);
        titlemore_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final ImageView img = (ImageView) v;
                //构造数据
                Map<AbMenuItem, AbMenuItem> map1 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map2 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map3 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map4 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map5 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map6 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map7 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map8 = new HashMap<AbMenuItem, AbMenuItem>();
                map1.put(new AbMenuItem("　单据号："), new AbMenuItem(qgdtitle.getCvouchid()));
                map2.put(new AbMenuItem("请购日期："), new AbMenuItem(qgdtitle.getDdate()));
                map3.put(new AbMenuItem("请购部门："), new AbMenuItem(qgdtitle.getCdepname()));
                map4.put(new AbMenuItem("请购类别："), new AbMenuItem(qgdtitle.getCqgtype()));
                map5.put(new AbMenuItem("审批流程："), new AbMenuItem(qgdtitle.getLinename()));
                map6.put(new AbMenuItem("　审批人："), new AbMenuItem(qgdtitle.getCchecker()));
                map7.put(new AbMenuItem("审批时间："), new AbMenuItem(Basenvo.customDateFormat("yyyy-MM-dd", qgdtitle.getCcheckdate())));
                map8.put(new AbMenuItem("　总金额："), new AbMenuItem(Basenvo.customFormat("######.00##", qgdtitle.getIamount())));
                ArrayList<Map<AbMenuItem, AbMenuItem>> data = new ArrayList<Map<AbMenuItem, AbMenuItem>>();
                data.add(map1);
                data.add(map2);
                data.add(map3);
                data.add(map4);
                data.add(map5);
                data.add(map6);
                data.add(map7);
                data.add(map8);
                ListPopAdapter mListPopAdapter = new ListPopAdapter(getApplicationContext(), data, R.layout.list_popitem);
                popListView.setAdapter(mListPopAdapter);

                //弹出窗口后,变更更多图标
                img.setImageResource(R.drawable.item_more_choose);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    public void onDismiss() {
                        //还原图标
                        img.setImageResource(R.drawable.item_more);
                    }
                });
                popupWindow.showAsDropDown(v);
            }
        });
    }

    //先获取审批流程
    private void getsplc() {
        //获取审批流程列表
        AbTask task = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskObjectListener() {

            @Override
            public <T> void update(T entity) {
                String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;//旧版webservice地址
                AbSoapParams params = new AbSoapParams();
                params.put("arg0", myApplication.getGs_ztid());
                params.put("arg1", myApplication.getGs_year());
                params.put("arg2", qgdtitle.getCvouchid());
                mAbSoapUtil.call(urlString, InstorageURL.NAME_SPACE, "getqgdsplclines", params, new AbSoapListener() {
                    //获取数据成功会调用这里
                    @Override
                    public void onSuccess(int statusCode, String content) {
                        int checktag = 0;//待审步骤标记
                        String lastcharname = "";
                        if (content != null) {
                            splclineslist = abXMLSplcCharlist.paraseCommentInfors(content);
                            //忽略第一行,录入步骤
                            for (int i = 1; i < splclineslist.size(); i++) {
                                SplcLinesChar splcline = splclineslist.get(i);
                                String listnote = "(" + splcline.getCharcode() + ")" + splcline.getCharname();
                                //显示当前待审字样式
                                if (checktag == 0 && splcline.getCchecker().equals("")) {
                                    checktag = 1;
                                    listnote = listnote + "[当前待审]";
                                }
                                //默认选择的行
                                if (qgdtitle.getIinorder().equals(splcline.getInorder())) {
                                    lastcharname = listnote;
                                }
                                list_splc.add(listnote);
                            }
                        } else {
                            AbToastUtil.showToast(qgdsp_detail.this, R.string.sqlerrormsg);
                        }
                        //使用这个函数直接根据返回结果刷新列表
                        adapter_splc.notifyDataSetChanged();
                        if (!lastcharname.equals("")) {
                            setSpinnerItemSelectedByValue(splcstep_sp, lastcharname);
                        }
                    }

                    // 失败，调用
                    @Override
                    public void onFailure(int statusCode, String content,
                                          Throwable error) {
                        AbToastUtil.showToast(qgdsp_detail.this, R.string.sqlerrormsg);
                    }

                    // 开始执行前
                    @Override
                    public void onStart() {
                        //显示进度框
                        AbDialogUtil.showProgressDialog(qgdsp_detail.this, 0, "正在加载...");
                    }


                    // 完成后调用，失败，成功
                    @Override
                    public void onFinish() {
                        //移除进度框
                        AbDialogUtil.removeDialog(qgdsp_detail.this);
                    }
                });
            }

            @SuppressWarnings("unchecked")
            @Override
            public Integer getObject() {
                return -1;
            }
        });
        task.execute(item);
    }

    public void refreshTask() {
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListener() {

            @Override
            public void update() {
                String iinorder = "0";
                if (splcstep_sp.getTag() == null || splcstep_sp.getTag().equals("")) {
                    //AbDialogUtil.removeDialog(qgdsp_detail.this);
                    return;
                }
                iinorder = splclineslist.get(Integer.valueOf(splcstep_sp.getTag().toString())).getInorder();

                //参数
//                String[] parms = {"cacc_id", "iyear", "cvouchid", "iinorder"};
//                String[] vals = {(String) myApplication.getGs_ztid(), (String) myApplication.getGs_year(), qgdtitle.getCvouchid(), iinorder};
//                //生成xml
//                BuildQgdListXMLService service = new BuildQgdListXMLService();
//                String xmlstring = service.buildXML(null, "qgddj_detaillist", InstorageURL.NAME_SPACE, parms, vals, null);
//                ToolSOAPxml.callService("qgddj_detaillist", xmlstring, new ToolSOAPxml.WebServiceCallBack() {
//                    @Override
//                    public void onSucced(String result) {
//                        if (result != null) {
//                            //解析xml文件,返回列表
//                            qgdlist_detail = XMLQgdDjdetail.paraseCommentInfors(result);
//                            //默认显示第一行数据
//                            if (qgdlist_detail.size() > 0) {
//                                //根据审批记录更新title中的审核人信息
//                                qgdtitle.setCchecker(qgdlist_detail.get(0).getCchecker());
//                                qgdtitle.setCcheckdate(qgdlist_detail.get(0).getCcheckdate());
//                                //==
//                                insert_data(0);
//                            }
//                        } else {
//                            AbToastUtil.showToastInThread(getApplicationContext(), R.string.sqlerrormsg);
//                        }
//                        AbDialogUtil.removeDialog(qgdsp_detail.this);
//                    }
//
//                    @Override
//                    public void onFailure(String result) {
//                        AbDialogUtil.removeDialog(qgdsp_detail.this);
//                        AbToastUtil.showToastInThread(getApplicationContext(), R.string.sqlerrormsg);
//                    }
//                });
//                mAbPullToRefreshView.onHeaderRefreshFinish();

                String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;//旧版webservice地址
                AbSoapParams params = new AbSoapParams();
                params.put("arg0", myApplication.getGs_ztid());
                params.put("arg1", myApplication.getGs_year());
                params.put("arg2", qgdtitle.getCvouchid());
                params.put("arg3", iinorder);
                mAbSoapUtil.call(urlString, InstorageURL.NAME_SPACE, "qgddj_detaillist", params, new AbSoapListener() {
                    //获取数据成功会调用这里
                    @Override
                    public void onSuccess(int statusCode, String content) {
                        int checktag = 0;//待审步骤标记
                        String lastcharname = "";
                        if (content != null) {
                            //解析xml文件,返回列表
                            qgdlist_detail = abXMLQgdDjdetail.paraseCommentInfors(content);
                            //默认显示第一行数据
                            if (qgdlist_detail.size() > 0) {
                                for (int i = 0; i < qgdlist_detail.size(); i++) {
                                    if ("0".equals(qgdlist_detail.get(i).getBapprove())) {
                                        qgdlist_detail.get(i).setFlag("false");
                                    } else {
                                        qgdlist_detail.get(i).setFlag("true");
                                    }
                                }
                                //根据审批记录更新title中的审核人信息
                                qgdtitle.setCchecker(qgdlist_detail.get(0).getCchecker());
                                qgdtitle.setCcheckdate(qgdlist_detail.get(0).getCcheckdate());
                                //==
                                insert_data(0);
                            }
                        } else {
                            AbToastUtil.showToast(qgdsp_detail.this, R.string.sqlerrormsg);
                        }
                        AbDialogUtil.removeDialog(qgdsp_detail.this);
                    }

                    // 失败，调用
                    @Override
                    public void onFailure(int statusCode, String content,
                                          Throwable error) {
                        AbToastUtil.showToast(qgdsp_detail.this, R.string.sqlerrormsg);
                    }

                    // 开始执行前
                    @Override
                    public void onStart() {
                        //显示进度框
                        //AbDialogUtil.showProgressDialog(qgdsp_detail.this, 0, "正在加载...");
                    }


                    // 完成后调用，失败，成功
                    @Override
                    public void onFinish() {
                        //移除进度框
                        AbDialogUtil.removeDialog(qgdsp_detail.this);
                    }
                });
//                mAbPullToRefreshView.onHeaderRefreshFinish();
            }

            @Override
            public void get() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
        });
        mAbTask.execute(item);
    }

    //为窗口填充数据
    public void insert_data(int listrow) {
        qgds = qgdlist_detail.get(listrow);
        if ("0".equals(qgds.getBapprove()) && "false".equals(qgds.getFlag())) {
            bapprove_rg.getChildAt(0).setEnabled(false);
        } else {
            bapprove_rg.getChildAt(0).setEnabled(true);
        }
        if (listtype.equals("0")) {
            //未定价时,默认进入的就是修改状态。经过测试，发现之前的操作模式太过繁琐
            showwin(true);
        } else {
            showwin(false);
        }
        icurrentrow = listrow;
        //填充数据
        //行号
        tv_currentrow.setText((icurrentrow + 1) + "/" + (qgdlist_detail.size()));
        //不可修改部分
        cinvname_tv.setText(qgds.getCinvname());
        cinvunit_tv.setText(qgds.getCinvm_unit());
        cinvstd_tv.setText(qgds.getCinvstd());
        iqgq_tv.setText(Basenvo.customFormat("######.00##", qgds.getIqgq()));

        //可修改部分
        iquantity_tv.setText(Basenvo.customFormat("######.00##", qgds.getIquantity()));
        cven_tv.setText(qgds.getCvenname());
        cven_tv.setTag(qgds.getCvencode());
        iprice_et.setText(Basenvo.customFormat("######.00##", qgds.getIprice()));
        iamount_tv.setText(Basenvo.customFormat("######.00##", qgds.getIamount()));
        cdisapprovereason_et.setText(qgds.getCdisapprovereason());

        if (Basenvo.equal(qgds.getBapprove(), "0")) {
            bapprove_rg.check(R.id.no_rb);
        } else {
            bapprove_rg.check(R.id.yes_rb);
        }
        //明细扩展信息
        insert_data_detail();
    }

    public void insert_data_detail() {
        //存货扩展信息弹窗
        ImageView listmore_iv = (ImageView) findViewById(R.id.listmore_iv);
        listmore_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final ImageView imgs = (ImageView) v;
                Map<AbMenuItem, AbMenuItem> map1 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map2 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map3 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map4 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map5 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map6 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map7 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map8 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map9 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map10 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map11 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map12 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map13 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map14 = new HashMap<AbMenuItem, AbMenuItem>();
                map1.put(new AbMenuItem("申请到货日期："), new AbMenuItem(qgds.getDdate_dh()));
                map2.put(new AbMenuItem("  待选供应商1："), new AbMenuItem(qgds.getCvennamep1()));
                map3.put(new AbMenuItem("      待选单价1："), new AbMenuItem(qgds.getIpricep1()));
                map4.put(new AbMenuItem("  待选供应商2："), new AbMenuItem(qgds.getCvennamep2()));
                map5.put(new AbMenuItem("      待选单价2："), new AbMenuItem(qgds.getIpricep2()));
                map6.put(new AbMenuItem("  待选供应商3："), new AbMenuItem(qgds.getCvennamep3()));
                map7.put(new AbMenuItem("      待选单价3："), new AbMenuItem(qgds.getIpricep3()));
                map8.put(new AbMenuItem("    自定义项二："), new AbMenuItem(qgds.getCdefine2()));
                map9.put(new AbMenuItem("    自定义项三："), new AbMenuItem(qgds.getCdefine3()));
                map10.put(new AbMenuItem("　        现存量："), new AbMenuItem(Basenvo.customFormat("######.00##", qgds.getIlquantity())));
                map11.put(new AbMenuItem("　    上月用量："), new AbMenuItem(Basenvo.customFormat("######.00##", qgds.getAvgiquantity())));
                map12.put(new AbMenuItem("　    最近入库："), new AbMenuItem(qgds.getDdate()));
                map13.put(new AbMenuItem("　    最近单价："), new AbMenuItem(qgds.getIlprice()));
                map14.put(new AbMenuItem("　最近供应商："), new AbMenuItem(qgds.getClvencode()));
                ArrayList<Map<AbMenuItem, AbMenuItem>> data = new ArrayList<Map<AbMenuItem, AbMenuItem>>();
                data.add(map1);
                data.add(map2);
                data.add(map3);
                data.add(map4);
                data.add(map5);
                data.add(map6);
                data.add(map7);
                data.add(map8);
                data.add(map9);
                data.add(map10);
                data.add(map11);
                data.add(map12);
                data.add(map13);
                data.add(map14);
                ListPopAdapter mListPopAdapter = new ListPopAdapter(getApplicationContext(), data, R.layout.list_popitem);
                popListView.setAdapter(mListPopAdapter);
                //弹出窗口后,变更更多图标
                imgs.setImageResource(R.drawable.item_more_choose);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    public void onDismiss() {
                        //还原图标
                        imgs.setImageResource(R.drawable.item_more);
                    }
                });
                popupWindow.showAsDropDown(v);
            }
        });
    }

    //供应商选择
    public void cven_choose(View v) {
        String btntype = v.getTag().toString();
        String cvencode = "";
        if (btntype.equals("cven")) {
            cvencode = cven_tv.getTag().toString();
        }
        Intent intent = new Intent(getApplicationContext(), Basenvo_Choosecven.class);
        // 设置传递数据
        intent.putExtra("btntype", btntype);
        intent.putExtra("ccode", cvencode);
        startActivityForResult(intent, R.layout.basenvo_rchoose / 200000);
    }

    //存货切换
    public void more_list(View v) {
        updatedataref();
        Intent intent = new Intent(getApplicationContext(), qgdsp_detaillist.class);
        //传递参数
        Bundle bundle = new Bundle();
        intent.putExtra("cinvcode", qgds.getCinvcode());
        bundle.putSerializable("detaillist", qgdlist_detail);
        bundle.putSerializable("qgdtitle", qgdtitle);//单据表头
        bundle.putSerializable("listtype", listtype);//未定价/已定价
        intent.putExtras(bundle);
        intent.putExtra("currentrow", "" + icurrentrow);//当前存货行号
        startActivityForResult(intent, R.layout.layout_qgddj_detaillist / 300000);
    }

    public void showwin(boolean stype) {
        //背景变白，字变黑色
        iquantity_tv.setEnabled(stype);
        cven_tv.setEnabled(stype);
        iprice_et.setEnabled(stype);
        cdisapprovereason_et.setEnabled(stype);
        if (stype) {
            //iquantity_tv.setBackgroundResource(R.drawable.edit_background);
            iquantity_tv.setBackgroundResource(R.drawable.edit_background);
            cven_tv.setBackgroundResource(R.drawable.edit_background);
            iprice_et.setBackgroundResource(R.drawable.edit_background);
            cdisapprovereason_et.setBackgroundResource(R.drawable.edit_background);
        } else {
            int textcolor = textcolor_old;
            Integer backgroundcolor = Color.TRANSPARENT;

            iquantity_tv.setTextColor(textcolor);
            iquantity_tv.setBackgroundColor(backgroundcolor);

            cven_tv.setTextColor(textcolor);
            cven_tv.setBackgroundColor(backgroundcolor);

            iprice_et.setTextColor(textcolor);
            iprice_et.setBackgroundColor(backgroundcolor);

            //iamount_tv.setEnabled(stype);
            //iamount_tv.setTextColor(textcolor);
            //iamount_tv.setBackgroundColor(backgroundcolor);
            cdisapprovereason_et.setTextColor(textcolor);
            cdisapprovereason_et.setBackgroundColor(backgroundcolor);
        }
    }

    //对一些修改后的值进行处理,避免因为没触发事件导致保存的信息不正确
    public void updatedataref() {
        String iquantity = iquantity_tv.getText().toString();
        String iprice = iprice_et.getText().toString();
        if (iquantity == null || iquantity.equals("") || iprice.equals("")) {
            iamount_tv.setText(Basenvo.customFormat("######.00##", "0"));
        } else {
            Double a = Double.valueOf(iquantity);
            Double b = Double.valueOf(iprice);
            iamount_tv.setText(Basenvo.customFormat("######.00##", Double.valueOf(iquantity) * Double.valueOf(iprice)));
        }
        //保存修改内容
        if (iquantity_tv.getText() != null) {
            qgds.setIquantity(iquantity_tv.getText().toString());
        } else {
            qgds.setIquantity("");
        }

        if (cven_tv.getTag() != null) {
            qgds.setCvencode(cven_tv.getTag().toString());
            qgds.setCvenname(cven_tv.getText().toString());
        } else {
            qgds.setCvencode("");
            qgds.setCvenname("");
        }

        if (iprice_et.getText() != null) {
            qgds.setIprice(iprice_et.getText().toString());
        } else {
            qgds.setIprice("");
        }

        if (iamount_tv.getText() != null) {
            qgds.setIamount(iamount_tv.getText().toString());
        } else {
            qgds.setIamount("");
        }

        if (cdisapprovereason_et.getText() != null) {
            qgds.setCdisapprovereason(cdisapprovereason_et.getText().toString());
        } else {
            qgds.setCdisapprovereason("");
        }
        //是否通过
        RadioButton yes_rb = (RadioButton) findViewById(R.id.yes_rb);
        if (yes_rb.isChecked()) {
            qgds.setBapprove("1");
        } else {
            qgds.setBapprove("0");
        }
    }

    //请购单审核
    public void qgdsp_check(View v) {
        updatedataref();
        //只有当前是最后一步时才需要判断
        if (qgdtitle.getStepall().equals(qgdtitle.getIinorder())) {
            //逐行检查明细数据是否存在问题
            for (int i = 0; i < qgdlist_detail.size(); i++) {
                UffjqgdList_detail qgds = qgdlist_detail.get(i);
                if (!qgds.getBclose().equals("1") && !qgds.getBapprove().equals("0")) {
                    //检查供应商
                    if (qgds.getCvencode().equals("")) {
                        AbToastUtil.showToast(getApplicationContext(), "第" + String.valueOf((i + 1)) + "行的供应商不能为空!");
                        return;
                    }
                    //检查单价
                    if (qgds.getIprice().equals("")) {
                        AbToastUtil.showToast(getApplicationContext(), "第" + String.valueOf((i + 1)) + "行的单价不能为空!");
                        return;
                    }
                }
            }
        }
        String urlString = "http://" + InstorageURL.SERVERURL
                + BaseUrl_New;
        String[] parms = {"user", "cacc_id", "iyear", "cvouchid", "charname", "stepall", "linecode", "istep", "type"};
        String[] vals = {User.nickName, (String) myApplication.getGs_ztid(), (String) myApplication.getGs_year(), qgdtitle.getCvouchid(), qgdtitle.getCchar(), qgdtitle.getStepall(), qgdtitle.getCnocheckreason(), qgdtitle.getIinorder(), "0"};
        //生成xml
        BuildQgdDjdetailXMLService service = new BuildQgdDjdetailXMLService();
        String xmlstring = service.buildXML(qgdlist_detail, "qgdsp_check", InstorageURL.NAME_SPACE, parms, vals, "in" + vals.length);
        mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "qgdsp_check", xmlstring, new AbSoapUtil.WebServiceCallBack() {
            @Override
            public void onSucced(String result) {
                if (result != null) {
                    //解析xml文件,返回列表
                    qgdlist_detail = XMLQgdDjdetail.paraseCommentInfors(result);
                    //默认显示第一行数据
                    if (qgdlist_detail.size() > 0) {
                        insert_data(0);
                        String succount = qgdlist_detail.get(0).getSuccount();
                        if (succount.equals("0")) {
                            AbToastUtil.showToast(getApplicationContext(), "请购单审批失败！");
                        } else if (succount.equals("-101") || succount.equals("-201")) {
                            AbToastUtil.showToast(getApplicationContext(), "您没有这一步审批角色的权限，不能操作！");
                        } else if (succount.equals("-102")) {
                            AbToastUtil.showToast(getApplicationContext(), "单据的上一步骤已经被取消审批了，不能继续审批！");
                        } else if (succount.equals("-202")) {
                            AbToastUtil.showToast(getApplicationContext(), "单据的下一步骤已经审批通过了，不能取消审批！");
                        } else if (succount.equals("-203")) {
                            AbToastUtil.showToast(getApplicationContext(), "此请购单已有记录生成了采购订单，不能取消审批！");
                        } else {
                            AbToastUtil.showToast(getApplicationContext(), "请购单审批成功！");
                            //成功之后返回主界面并刷新
                            Intent intent = new Intent();
                            intent.putExtra("isref", "1");//是否需要刷新当前列表
                            setResult(R.layout.layout_qgdsp_detail / 100000, intent);  //设置返回结果
                            finish();
                        }
                    }
                } else {
                    AbToastUtil.showToast(getApplicationContext(), "请购单定价保存失败，数据库错误！");
                }
                //AbDialogUtil.removeDialog(qgdsp_detail.this);
            }

            @Override
            public void onFailure(String result) {
                AbToastUtil.showToast(getApplicationContext(), "请购单定价保存失败!");
                //AbDialogUtil.removeDialog(qgdsp_detail.this);
            }
        });
    }

    //反审核操作
    public void qgd_uncheck(View v) {
        if (!Basenvo.equal(qgdtitle.getCchecker(), User.nickName) && (!Basenvo.equal(myApplication.getGs_option2().getQgd_dd_check(), "Y"))) {
            AbToastUtil.showToast(getApplicationContext(), "不能取消他人审批的单据!");
            return;
        }
        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;
        String[] parms = {"user", "cacc_id", "iyear", "cvouchid", "charname", "stepall", "linecode", "istep"};
        String[] vals = {User.nickName, (String) myApplication.getGs_ztid(), (String) myApplication.getGs_year(), qgdtitle.getCvouchid(), qgdtitle.getCchar(), qgdtitle.getStepall(), qgdtitle.getCnocheckreason(), qgdtitle.getCdefine4()};//消审的步骤Cdefine4
        //生成xml
        BuildQgdDjdetailXMLService service = new BuildQgdDjdetailXMLService();
        String xmlstring = service.buildXML(qgdlist_detail, "qgdsp_uncheck", InstorageURL.NAME_SPACE, parms, vals, "in" + vals.length);
        mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "qgdsp_uncheck", xmlstring, new AbSoapUtil.WebServiceCallBack() {
            @Override
            public void onSucced(String result) {
                if (result != null) {
                    //解析xml文件,返回列表
                    qgdlist_detail = XMLQgdDjdetail.paraseCommentInfors(result);
                    //默认显示第一行数据
                    String succount = qgdlist_detail.get(0).getSuccount();
                    if (succount.equals("0")) {
                        AbToastUtil.showToast(getApplicationContext(), "请购单审批失败");
                    } else if (succount.equals("-101") || succount.equals("-201")) {
                        AbToastUtil.showToast(getApplicationContext(), "您没有这一步审批角色的权限，不能操作!");
                    } else if (succount.equals("-102")) {
                        AbToastUtil.showToast(getApplicationContext(), "单据的上一步骤已经被取消审批了，不能继续审批!");
                    } else if (succount.equals("-202")) {
                        AbToastUtil.showToast(getApplicationContext(), "单据的下一步骤已经审批通过了，不能取消审批！");
                    } else if (succount.equals("-203")) {
                        AbToastUtil.showToast(getApplicationContext(), "此请购单已有记录生成了采购订单，不能取消审批！");
                    } else {
                        AbToastUtil.showToast(getApplicationContext(), "请购单消审成功");
                        //完成应该是关闭当前页面返回到上层
                        Intent intent = new Intent();
                        intent.putExtra("isref", "1");//是否需要刷新当前列表
                        setResult(R.layout.layout_qgdsp_detail / 100000, intent);  //设置返回结果
                        finish();
                    }
                } else {
                    AbToastUtil.showToast(getApplicationContext(), "请购单审批失败!数据库错误!");
                }
                //AbDialogUtil.removeDialog(qgdsp_detail.this);
            }

            @Override
            public void onFailure(String result) {
                AbToastUtil.showToast(getApplicationContext(), "请购单消审失败");
                //AbDialogUtil.removeDialog(qgdsp_detail.this);
            }
        });
    }

    //接收返回数据(供应商和存货明细)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case R.layout.basenvo_rchoose / 200000:
                if (data != null) {
                    //刷新list
                    venlist = myApplication.getGv_vendor();
                    Bundle bundle = data.getExtras();
                    String cvencode = bundle.getString("cvencode");
                    String cvenname = bundle.getString("cvenname");
                    String btntype = bundle.getString("btntype");
                    if (btntype.equals("cven")) {
                        //供应商则必须从列表中获取.
                        cven_tv.setText(cvenname);
                        cven_tv.setTag(cvencode);
                        qgds.setCvencode(cvencode);
                        qgds.setCvenname(cvenname);
                    }
                }
                break;
            case R.layout.layout_qgddj_detaillist / 300000:
                Bundle bundle = data.getExtras();
                String listrow = bundle.getString("listrow");
                if (listrow.equals("-100")) {
                    //退回成功,关闭当前,并刷新列表
                    Intent intent = new Intent();
                    intent.putExtra("isref", "1");//是否需要刷新当前列表
                    setResult(R.layout.layout_qgdsp_detail / 100000, intent);  //设置返回结果
                    this.finish();
                } else {
                    //更换明细
                    qgdlist_detail = (ArrayList<UffjqgdList_detail>) data.getSerializableExtra("detaillist");
                    qgdtitle = (UffjqgdList) data.getSerializableExtra("qgdtitle");
                    insert_data(Integer.valueOf(listrow));
                }
            default:
                //其它窗口的回传数据
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //根据值选择下拉列表
    public static void setSpinnerItemSelectedByValue(Spinner spinner, String value) {
        SpinnerAdapter apsAdapter = spinner.getAdapter(); //得到SpinnerAdapter对象
        int k = apsAdapter.getCount();
        for (int i = 0; i < k; i++) {
            if (value.equals(apsAdapter.getItem(i).toString())) {
                spinner.setSelection(i, true);// 默认选中项
                break;
            }
        }
    }

    //向左翻页
    public void btn_abs_back(View v) {
        updatedataref();
        if (icurrentrow == 0) {
            AbToastUtil.showToast(getApplicationContext(), "已经是第一项");
        } else {
            insert_data(icurrentrow - 1);
        }
    }

    //向右翻页
    public void btn_abs_forward(View v) {
        updatedataref();
        if (icurrentrow == (qgdlist_detail.size() - 1)) {
            AbToastUtil.showToast(getApplicationContext(), "已经是最后一项");
        } else {
            insert_data(icurrentrow + 1);
        }
    }

    @Override
    public void onFooterLoad(AbPullToRefreshView abPullToRefreshView) {
        refreshTask();
    }

    @Override
    public void onHeaderRefresh(AbPullToRefreshView abPullToRefreshView) {
        refreshTask();
    }
}
